<script lang="ts" setup>
  import { useParamsListQuery } from '@/hooks/paramsListQuery'
  import { TableOptions } from '@/types/dataTable'
  import { nextTick, reactive, ref, watch } from 'vue'
  import { Bell, Search, Delete, Edit, Plus, ArrowUp } from '@element-plus/icons-vue'
  import { useDictForm } from '../hooks/useDictItems'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { addDictService, deleteDicData, updateDictService } from '@/api/dict'
  import { DictItem } from '@/types/dict'

  const { listQuery } = useParamsListQuery()
  const { DictForm, refForm, rules, resetForm } = useDictForm()
  const dialogVisible = ref<boolean>(false)
  const dictTable = ref()
  const typeNumber = ref<boolean>(false) // 用于区分字典类型
  const isEdit = ref<boolean>(false)
  const options = reactive<TableOptions>({
    add: {
      enable: true,
      permission: '',
    },
    edit: {
      enable: false,
      permission: '',
    },
    delete: {
      enable: false,
      permission: '',
      url: '/dict/deleteDicData',
    },
    listUrl: '/dict/getDicData', // 列表请求URL
  })
  interface props {
    visible: boolean
    postForm: Partial<DictItem>
  }
  const props = withDefaults(defineProps<props>(), {
    visible: false,
    dicCode: '',
    title: '',
  })
  const emit = defineEmits<{
    // (e: 'closeDrawer', val: boolean): void
    (e: 'update:visible', val: boolean): void
  }>()
  const closeDrawer = () => {
    // emit('closeDrawer', false)
    emit('update:visible', false)
  }
  watch(
    () => props.visible,
    (val) => {
      dialogVisible.value = val
    },
  )
  watch(
    () => props.postForm.dictCode,
    (newDicCode) => {
      listQuery.value.params.name = newDicCode
    },
    { immediate: true },
  )
  watch(
    () => props.postForm.id,
    (newPid) => {
      listQuery.value.params.id = newPid
    },
    { immediate: true },
  )
  // 监视type值的类型
  watch(
    () => props.postForm.type,
    (newType) => {
      typeNumber.value = newType === '数据字典'
    },
    { immediate: true },
  )
  //============字典弹框
  const openDicDialog = (type: number, val?: DictItem) => {
    resetForm()
    switch (type) {
      case 0: // 新增分类
        isEdit.value = false
        diaLogDict.value = true
        DictForm.value.pid = props.postForm.id || ''
        break
      case 1: //新增下一级字典
        isEdit.value = false
        diaLogDict.value = true
        DictForm.value.pid = val?.id
        break
      case 2: // 修改
        isEdit.value = true
        diaLogDict.value = true
        nextTick(() => {
          Object.assign(DictForm.value, val)
        })
        break
      case 3: // 删除
        ElMessageBox.confirm('是否确认删除该字典项？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          await deleteDicData([val!.id])
          ElMessage.success('字典项删除成功')
          listQuery.value.pageNum = 1 // 重置分页
          dictTable.value?.getList()
        })
        return
      default:
        ElMessage.error('未知的操作类型')
        break
    }
  }

  const diaLogDict = ref<boolean>(false)
  const submit = async () => {
    refForm.value.validate(async (valid) => {
      if (valid) {
        DictForm.value.dictCode = props.postForm.dictCode
        DictForm.value.type = props.postForm.type
        isEdit.value ? await updateDictService(DictForm.value) : await addDictService(DictForm.value)
        isEdit.value ? ElMessage.success('字典项更新成功') : ElMessage.success('字典项添加成功')
        diaLogDict.value = false
        dictTable.value?.getList()
      }
    })
  }
</script>

<template>
  <el-dialog v-model="diaLogDict" title="字典项" top="40vh" width="30%">
    <el-form ref="refForm" :model="DictForm" :rules="rules" label-width="70px" class="justify-label" status-icon>
      <el-form-item label="名称" prop="name">
        <el-input id="dict-name" v-model="DictForm.name" placeholder="显示的名称" />
      </el-form-item>
      <el-form-item v-if="typeNumber" label="字典值" prop="value">
        <el-input id="dict-value" v-model.number="DictForm.value" placeholder="字典的值" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input id="dict-desc" v-model="DictForm.desc" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="diaLogDict = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <el-drawer v-model="dialogVisible" :title="props.postForm.name" size="40%" :before-close="closeDrawer">
    <data-table ref="dictTable" v-model:list-query="listQuery" :options="options" @add="openDicDialog(0)">
      <template #filter-content>
        <el-input
          id="search-keyword"
          v-model.trim="listQuery.params.keyword"
          :prefix-icon="Search"
          style="width: 200px"
          placeholder="名称"
          class="filter-item"
        />
      </template>
      <template #data-columns>
        <el-table-column show-overflow-tooltip align="center" label="名称" prop="name" />
        <el-table-column v-if="typeNumber" show-overflow-tooltip align="center" label="字典值" prop="value" />
        <el-table-column show-overflow-tooltip align="center" label="排序" prop="sort" width="80">
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.sort || 1 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button plain size="small" title="添加下一级" type="success" :icon="Plus" circle @click="openDicDialog(1, scope.row)" />
            <el-button plain size="small" title="修改" type="primary" :icon="Edit" circle @click="openDicDialog(2, scope.row)" />
            <el-button plain size="small" title="删除" type="danger" :icon="Delete" circle @click="openDicDialog(3, scope.row)" />
          </template>
        </el-table-column>
      </template>
    </data-table>
  </el-drawer>
</template>
